<?php

/*
    8   _                          _      8
    8oo " 8""o 8  8 d"" ,+"+. ,+"" " """. 8
    8   8 8  8 8  8 "+, 8   8 8    8 d""8 8
    'oo 8 8  8 `""8 oo? '+o+' '+oo 8 "oo8 8
               "oo'
    
    THE SOCIAL NETWORK THAT CAN TWEET ITSELF!
    
  (actually it takes eight tweets but still...)

/**
 *
 * @author Julio Sepia <jsepia@juliosepia.com>
 *
 */



/**
 * r
 * read $x records of a file into an array
 * @param $n Filename
 * @param $r Record length
 * @param $x How many records
 */
function r($n,$r,$x){$z=array();$f=fopen($n,'rb');$x?fseek($f,-$x*$r,SEEK_END):NULL;while(!feof($f))$z[]=fread($f,$r);fclose($f);return $z;}

/**
 * s
 * read and return a file as an html list
 * @param $n Filename
 * @param $r Record length
 */
function s($n,$r){$z='<ul>';$x=array_map('trim',str_split(file_get_contents($n),$r));foreach($x as $y)$z.="<li>$y</li>";return"$z</ul>";}

/**
 * f
 * Return a form with a textbox
 * @param $n Textbox name
 * @param $s Maxlength
 */
session_start();function f($n,$s){return '<form action="" method="POST"><input type="text" name="'.$n.'" maxlength="'.$s.'"></form>';}

/**
 * Do login (set the $_SESSION['u'] variable to the value of the $_POST['u'] variable, or itself)
 */
@mkdir('f');@mkdir('t');$_SESSION['u']=isset($_POST['u'])?$_POST['u']:u();foreach(array('t','p') as $i){isset($_POST[$i])?$i():NULL;}

/**
 * l
 * Return the login form
 */
echo isset($_SESSION['u'])?p():l();function l(){return 'Who are you? '.f('u',14);}function u(){return $_SESSION['u'];}

/**
 * p
 * Return a user's timeline (by default, the current user, unless the URL has the 'p' parameter)
 */
function p(){$p=isset($_GET['p'])?$_GET['p']:u();return (($p==u())?(u().':<br>'.f('t',140)):'').s("t/$p",156);}isset($_GET['f'])?w():'';

/**
 * t
 * Adds a message from the current user to all his followers' timelines
 * Takes the message from the $_POST['t'] variable
 */
/**
 * w
 * Follows an user. The user to follow should be in the $_GET['f'] variable.
 * This function adds the current user to the followed user's list of followers.
 */
function t(){$m=$_POST['t'];$f=r('f/'.u(),14,0);foreach($f as $i){a("t/$i",u().": $m",156);}}function w(){a('f/'.$_GET['f'],u(),14);}

/**
 * a
 * Append a string to a file.
 * @param $n Filename
 * @param $m Message
 * @param $r Record length
 */
function a($n,$m,$r){@file_put_contents($n,str_pad($m,$r),FILE_APPEND);}

?>